<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Users;
use App\Model\TempPhone;
use App\Model\User_login_info;
use App\Model\Suggestmessage;
use App\Http\Controllers\Api\Common;
use Illuminate\Support\Facades\Redis;
use App\Model\Settings;

class UserController extends Controller
{
    public function json($code,$data=[])
    {
        return response()->json([
            'status' => $code,
            'data' => $data,
            ]);
    }

    /**
    * @author 区汉东 <[<765879595@qq.com>]>
    * 对用户名进行判断
    */

   public function nameManage()
   {

    $name = $_POST['name'];

    $user = Users::select(['id','name','password'])
        ->where('name',$name)
        ->first();

        if ($user) {
            echo 1;
        }else{
            echo 2;
        }
   }

    /**
    * @author 区汉东 <[<765879595@qq.com>]>
    * 对手机号进行判断
    */
    public function phoneManage()
    {
       	$phone = $_POST['phone'];
        $userPhone = Users::select(['id','name','phone'])
        ->where('phone',$phone)
        ->first();

        //判断手机号是否存在
        if ($userPhone) {
            echo 1;
        } else {
            echo 2;
        }
    }


    /**
    * @author 区汉东 <[<765879595@qq.com>]>
    * 对邮箱进行判断
    */
    public function emailManage()
    {
       	$email = $_POST['email'];
       	// $patten ='/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/';
       	$userEmail = Users::select(['id','name','email'])
        ->where('email',$email)
        ->first();
        // 判断邮箱是否存在
        if ($userEmail) {
            echo 1;
        }else{
            echo 2;
        }
    }

    /**
    * @author 区汉东 <[<765879595@qq.com>]>
    * 对手密码进行判断
    */
    public function passManage()
    {
        $pass = $_POST['pass'];
        // 密码正则
        $patten = '/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]{8,16}$/';
        // 判断密码是否匹配
        preg_match($patten,$pass,$match);

        if ($match) {
            echo 1;
        }else{
            echo 2;
        }		
   }
    /**
    * @author 区汉东 <[<765879595@qq.com>]>
    * 对手机验证码进行判断
    */
    public function codeManage()
    {
        $code = $_POST['code'];
        $phone =$_POST['phone'];
        $phoneCode = TempPhone::select('phone','code')
        ->where('phone',$phone)
        ->orderBy('id','desc')
        ->first();

        if ($code == $phoneCode->code) {

        echo 1;

        } else {

         echo 2;
        }
    }

    /**
    * @author 区汉东 <[<765879595@qq.com>]>
    * 实现注册
    */
    public function handerRegister()
    {

        // 接收传过来的注册信息 
       	$name = $_POST['name'];
       	$pass = $_POST['pass'];
        $set = Settings::select('registerCode')->first();
        $repass = $_POST['repass'];
        $email= $_POST['email'];
        $phone= $_POST['phone'];
        $code = $_POST['code'];

        // 判断用户是否为空
        if (!$name) {
           return $this->json(1501);
        }
        // 判断密码是否为空 
        if (!$pass) {
           return $this->json(1502);
        }
        // 判断确认密码是否为空
        if (!$repass) {
           return $this->json(15002);
        }
        // 判断邮箱是否为空
        if (!$email) {
           return $this->json(1503);
        } 
        // 判断手机是否为空
        if (!$phone) {
           return $this->json(1504);
        }
        // 判断验证码是否为空
        if (!$code) {
           return $this->json(1505);
        }

        //判断是普通验证码还是手机验证码
        if ($set->registerCode == 2) {
            if (session('code') != $code ) {
                return $this->json(1506);
            }
        } else {
            $phoneCode = TempPhone::select('phone','code')
            ->where('phone',$phone)
            ->orderBy('id','desc')
            ->first();
            // dd($code,$phoneCode->code);
            if ($code != $phoneCode->code) {
                return $this->json(1506);
            }
        }
        // 把用户数据写进数据库
        $bool = Users::insert([
            'name'=>$name,
            'password'=>password_hash($pass,PASSWORD_DEFAULT),
            'email'=>$email,
            'phone'=>$phone,
            'code'=>$code,
            'addtime' => time(),
            ]);
        // 判断是否有写进数据库
        if ($bool) {
        //注册成功
            return $this->json(1200);
        } else {
        //注册失败
            return $this->json(1500);
        }

    }

//======================登录功能=====================
   public function handerLogin()
   {
        // 接收用户提交的用户名密码验证码
        $name = $_POST['name'];
        $pass = $_POST['pass'];
        $code = $_POST['code'];

        // 判断验证码是否正确
        if (session()->get('code') != $code ) {
          // dd($code,session()->get('code'));
            return $this->json(1506);
        }
        // 判断用户名是否为空
        if (!$name) {
            return $this->json(1501);
        }
        // 判断密码是否为空
        if (!$pass) {
            return $this->json(1502);
        }

        // 从数据库查找用户
        $user = Users::select(['id','name','password','phone','email'])->where('name',$name)->first();
        // 判断用户是否存在
        if (!$user) {
        //用户不存在
        return $this->json(1404);

      } else {
      // 把用户数据存进session
      session()->put('user',array('id'=>$user->id,
              'name'=>$user->name,
              'email'=>$user->email,
              'phone'=>$user->phone
        ));
      }

    // dd($user->password);
	  //检查用户最近30分钟密码错误次数
	  $res = $this->checkPassWrongTime($user['id']);
	  // dd($res);
	  //错误次数超过限制次数
	  if ( $res === false ) {
		 return $this->json(1800);
		 exit;
	  }
	  //验证密码
	  // dd($pass,y);
	  if(password_verify($pass,$user->password)) {
				// 购物车同步
				$uid = session()->get("user")['id'];
				$session_id = session()->getId();
				$getRedis = Redis::get($session_id);
				$data = unserialize($getRedis);

				if(!empty($uid)){
					if(!empty($getRedis)){
						$user =  Redis::set($uid,$getRedis);
					}
				};
		 return $this->json(1200);

	  } else {
		 //记录密码错误次数
	    $this->recordPassWrongTime($user['id']);
         return $this->json(1402);
         exit;
       
        }

    }

    /**
    * @author 区汉东 <[<765879595@qq.com>]>
    * $uid 用户id
    * 记录密码输出信息
    */
    protected function recordPassWrongTime($uid)
    {
        //ip2long()函数将IP地址转换成数字
        $ip = ($_SERVER['REMOTE_ADDR']);
        $time = date('Y-m-d H:i:s');
        $sql = User_login_info::insert([
 'uid'=>$uid,
            'ipaddr'=>$ip,
            'logintime'=>$time,
            'pass_wrong_time_status'=>2,

         ]);
        }

    /**
    * 检查用户最近$min分钟密码错误次数
    * $uid 用户ID
    * $min  锁定时间
    * $wTIme 错误次数
    * @return 错误次数超过返回false,其他返回错误次数，提示用户
    */
    protected function checkPassWrongTime($uid,$min=1, $wTIme=3)
    {
        if ( empty($uid) ) {
            throw new \Exception("第一个参数不能为空");
        }

        $time = time();
        $prevTime = time() - $min*60;
        $finalTime = date('Y-m-d H:i:s', $time);
        $finalPrevTime = date('Y-m-d H:i:s', $prevTime);

        //用户所在登录ip
        $ip = ($_SERVER['REMOTE_ADDR']);
        // dd($prevTime,$time);
        // dd(date('Y-m-d H:i:s', $prevTime));
        // dd($finalPrevTime);
        $utime = User_login_info::select('uid','pass_wrong_time_status','ipaddr')
        ->where([
             ['uid',$uid],
             ['pass_wrong_time_status',2],
             ['ipaddr',$ip]
        ])
        ->whereBetween('logintime',[$finalPrevTime,$finalTime])
        ->count();
        //统计错误次数

        // var_dump($wrongTime);
        //判断错误次数是否超过限制次数
        if ( $utime >= $wTIme ) {
            return false;
        }
            return $utime;


    }

    public function __call($methodName, $params)
    {

        echo '访问的页面不存在','<a href="./login.php">返回登录页</a>';
        }

        public function logout() 
        {
        session()->flush();
        return redirect('/finallogin');

    }

    /**
    * @author 区汉东 <[<765879595@qq.com>]>
    * 处理意见反馈页面
    */ 
    public function dosuggest()
    {
        // dd($name,$email);
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];


        // 判断昵称是否为空
        if (!$name) {
            return $this->json(2000);
        }
        // 判断邮箱是否为空
        if (!$email) {
            return $this->json(2001);
        }   
        // 判断邮箱是否为空
        if (!$message) {
            return $this->json(2002);
        }

        // 把反馈信息写入数据库
        $total=Suggestmessage::insert([
        'name'=>$name,
        'email'=>$email,
        'message'=>$message,
        'addtime'=>time()
        ]);
        // dd($total);
        // 判断反馈信息是否写入成功
        if ($total) {
            return $this->json(2003); 
        }else {
            return $this->json(2004);
        }
    }
}
